"use client"

import { useState, useEffect } from "react"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Settings, Database, Palette, Sliders, LayoutGrid } from "lucide-react"
import { Switch } from "@/components/ui/switch"
import { Slider } from "@/components/ui/slider"
import { useToast } from "@/components/ui/use-toast"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Textarea } from "@/components/ui/textarea"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"

export function ChartConfig({ chart, onUpdate }) {
  const [title, setTitle] = useState(chart.title)
  const [labels, setLabels] = useState(chart.data.labels.join(", "))
  const [dataValues, setDataValues] = useState(chart.data.datasets[0].data.join(", "))
  const [datasetLabel, setDatasetLabel] = useState(chart.data.datasets[0].label)
  const [backgroundColor, setBackgroundColor] = useState(chart.data.datasets[0].backgroundColor || "#3498db")
  const [borderColor, setBorderColor] = useState(chart.data.datasets[0].borderColor || "#3498db")
  const [animation, setAnimation] = useState(chart.options.animation !== false)
  const [chartHeight, setChartHeight] = useState(chart.height || 2)
  const [chartWidth, setChartWidth] = useState(chart.width || 6)
  const [tension, setTension] = useState(chart.data.datasets[0].tension || 0)
  const [borderWidth, setBorderWidth] = useState(chart.data.datasets[0].borderWidth || 1)
  const [showLegend, setShowLegend] = useState(true)
  const [chartType, setChartType] = useState(chart.type)
  const { toast } = useToast()

  useEffect(() => {
    setTitle(chart.title)
    setLabels(chart.data.labels.join(", "))
    setDataValues(chart.data.datasets[0].data.join(", "))
    setDatasetLabel(chart.data.datasets[0].label)
    setBackgroundColor(chart.data.datasets[0].backgroundColor || "#3498db")
    setBorderColor(chart.data.datasets[0].borderColor || "#3498db")
    setAnimation(chart.options.animation !== false)
    setChartHeight(chart.height || 2)
    setChartWidth(chart.width || 6)
    setTension(chart.data.datasets[0].tension || 0)
    setBorderWidth(chart.data.datasets[0].borderWidth || 1)
    setChartType(chart.type)
  }, [chart])

  const handleSave = () => {
    const labelsArray = labels.split(",").map((label) => label.trim())
    const dataArray = dataValues.split(",").map((value) => Number.parseFloat(value.trim()))

    const updatedChart = {
      ...chart,
      title,
      type: chartType,
      height: chartHeight,
      width: chartWidth,
      data: {
        labels: labelsArray,
        datasets: [
          {
            ...chart.data.datasets[0],
            label: datasetLabel,
            data: dataArray,
            backgroundColor,
            borderColor,
            tension,
            borderWidth,
          },
        ],
      },
      options: {
        ...chart.options,
        animation,
        plugins: {
          ...chart.options.plugins,
          legend: {
            display: showLegend,
          },
        },
      },
    }

    onUpdate(updatedChart)

    toast({
      title: "图表已更新",
      description: "图表配置已成功应用",
    })
  }

  const handleDataImport = (jsonData) => {
    try {
      const data = JSON.parse(jsonData)
      if (data.labels && Array.isArray(data.labels)) {
        setLabels(data.labels.join(", "))
      }
      if (data.datasets && Array.isArray(data.datasets) && data.datasets[0]?.data) {
        setDataValues(data.datasets[0].data.join(", "))
        if (data.datasets[0].label) {
          setDatasetLabel(data.datasets[0].label)
        }
      }

      toast({
        title: "数据已导入",
        description: "JSON数据已成功导入",
      })
    } catch (error) {
      toast({
        title: "导入失败",
        description: "JSON格式不正确",
        variant: "destructive",
      })
    }
  }

  const chartTypeOptions = [
    { value: "bar", label: "柱状图" },
    { value: "line", label: "折线图" },
    { value: "pie", label: "饼图" },
    { value: "area", label: "面积图" },
    { value: "gauge", label: "仪表盘" },
    { value: "scatter", label: "散点图" },
    { value: "radar", label: "雷达图" },
    { value: "heatmap", label: "热力图" },
    { value: "bubble", label: "气泡图" },
    { value: "candlestick", label: "K线图" },
    { value: "treemap", label: "矩形树图" },
    { value: "funnel", label: "漏斗图" },
  ]

  return (
    <Card>
      <CardHeader className="pb-2">
        <CardTitle className="text-sm font-medium">图表配置</CardTitle>
      </CardHeader>
      <CardContent>
        <Tabs defaultValue="general">
          <TabsList className="grid w-full grid-cols-5">
            <TabsTrigger value="general" className="text-xs">
              <Settings className="h-3 w-3 mr-1" />
              常规
            </TabsTrigger>
            <TabsTrigger value="data" className="text-xs">
              <Database className="h-3 w-3 mr-1" />
              数据
            </TabsTrigger>
            <TabsTrigger value="style" className="text-xs">
              <Palette className="h-3 w-3 mr-1" />
              样式
            </TabsTrigger>
            <TabsTrigger value="layout" className="text-xs">
              <Sliders className="h-3 w-3 mr-1" />
              布局
            </TabsTrigger>
            <TabsTrigger value="advanced" className="text-xs">
              <LayoutGrid className="h-3 w-3 mr-1" />
              高级
            </TabsTrigger>
          </TabsList>

          <TabsContent value="general" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="title">图表标题</Label>
              <Input id="title" value={title} onChange={(e) => setTitle(e.target.value)} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="chartType">图表类型</Label>
              <Select value={chartType} onValueChange={setChartType}>
                <SelectTrigger id="chartType">
                  <SelectValue placeholder="选择图表类型" />
                </SelectTrigger>
                <SelectContent>
                  {chartTypeOptions.map((option) => (
                    <SelectItem key={option.value} value={option.value}>
                      {option.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            <div className="flex items-center space-x-2">
              <Switch id="animation" checked={animation} onCheckedChange={setAnimation} />
              <Label htmlFor="animation">启用动画</Label>
            </div>

            <div className="flex items-center space-x-2">
              <Switch id="showLegend" checked={showLegend} onCheckedChange={setShowLegend} />
              <Label htmlFor="showLegend">显示图例</Label>
            </div>
          </TabsContent>

          <TabsContent value="data" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="datasetLabel">数据系列名称</Label>
              <Input id="datasetLabel" value={datasetLabel} onChange={(e) => setDatasetLabel(e.target.value)} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="labels">标签 (逗号分隔)</Label>
              <Input id="labels" value={labels} onChange={(e) => setLabels(e.target.value)} />
            </div>

            <div className="grid gap-2">
              <Label htmlFor="dataValues">数据值 (逗号分隔)</Label>
              <Input id="dataValues" value={dataValues} onChange={(e) => setDataValues(e.target.value)} />
            </div>

            <Popover>
              <PopoverTrigger asChild>
                <Button variant="outline" size="sm" className="w-full">
                  导入JSON数据
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-80">
                <div className="grid gap-4">
                  <div className="space-y-2">
                    <h4 className="font-medium leading-none">JSON数据</h4>
                    <p className="text-sm text-muted-foreground">
                      粘贴符合Chart.js格式的JSON数据，包含labels和datasets字段
                    </p>
                  </div>
                  <Textarea
                    placeholder='{"labels":["一月","二月"],"datasets":[{"label":"销售额","data":[65,59]}]}'
                    className="h-24"
                    id="jsonData"
                  />
                  <Button
                    onClick={() => {
                      const jsonData = document.getElementById("jsonData").value
                      handleDataImport(jsonData)
                    }}
                  >
                    导入
                  </Button>
                </div>
              </PopoverContent>
            </Popover>
          </TabsContent>

          <TabsContent value="style" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="backgroundColor">背景颜色</Label>
              <div className="flex gap-2">
                <Input
                  type="color"
                  id="backgroundColor"
                  value={backgroundColor}
                  onChange={(e) => setBackgroundColor(e.target.value)}
                  className="w-12 h-8 p-1"
                />
                <Input
                  type="text"
                  value={backgroundColor}
                  onChange={(e) => setBackgroundColor(e.target.value)}
                  className="flex-1"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <Label htmlFor="borderColor">边框颜色</Label>
              <div className="flex gap-2">
                <Input
                  type="color"
                  id="borderColor"
                  value={borderColor}
                  onChange={(e) => setBorderColor(e.target.value)}
                  className="w-12 h-8 p-1"
                />
                <Input
                  type="text"
                  value={borderColor}
                  onChange={(e) => setBorderColor(e.target.value)}
                  className="flex-1"
                />
              </div>
            </div>

            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="borderWidth">边框宽度</Label>
                <span className="text-sm text-muted-foreground">{borderWidth}px</span>
              </div>
              <Slider
                id="borderWidth"
                min={0}
                max={10}
                step={1}
                value={[borderWidth]}
                onValueChange={(value) => setBorderWidth(value[0])}
              />
            </div>

            {(chartType === "line" || chartType === "area") && (
              <div className="grid gap-2">
                <div className="flex justify-between">
                  <Label htmlFor="tension">曲线平滑度</Label>
                  <span className="text-sm text-muted-foreground">{tension}</span>
                </div>
                <Slider
                  id="tension"
                  min={0}
                  max={1}
                  step={0.1}
                  value={[tension]}
                  onValueChange={(value) => setTension(value[0])}
                />
              </div>
            )}
          </TabsContent>

          <TabsContent value="layout" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="chartHeight">图表高度</Label>
                <span className="text-sm text-muted-foreground">{chartHeight}</span>
              </div>
              <Slider
                id="chartHeight"
                min={1}
                max={6}
                step={0.5}
                value={[chartHeight]}
                onValueChange={(value) => setChartHeight(value[0])}
              />
            </div>

            <div className="grid gap-2">
              <div className="flex justify-between">
                <Label htmlFor="chartWidth">图表宽度</Label>
                <span className="text-sm text-muted-foreground">{chartWidth}/12</span>
              </div>
              <Slider
                id="chartWidth"
                min={1}
                max={12}
                step={1}
                value={[chartWidth]}
                onValueChange={(value) => setChartWidth(value[0])}
              />
            </div>
          </TabsContent>

          <TabsContent value="advanced" className="space-y-4 pt-4">
            <div className="grid gap-2">
              <Label htmlFor="advancedConfig">高级配置</Label>
              <Textarea id="advancedConfig" placeholder="此功能正在开发中..." className="h-24" disabled />
            </div>
          </TabsContent>
        </Tabs>

        <Button onClick={handleSave} className="w-full mt-4">
          应用更改
        </Button>
      </CardContent>
    </Card>
  )
}
